<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 6.0.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/ficon.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/icon.png">
  <link rel="mask-icon" href="/images/icon.png" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-minimal.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"bqlin.github.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":true,"comments":{"style":"tabs","active":"gitalk","storage":true,"lazyload":false,"nav":{"gitalk":{"order":-2}},"activeClass":"gitalk"},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":-1,"unescape":false,"preload":false},"motion":{"enable":false,"async":true,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="方法调用的流程： objc_msgSend调用方法的本质是通过isa指针找到该类，然后寻找方法，找到后调用。如果没有找到则通过superClass找到父类，继续查找方法。">
<meta property="og:type" content="article">
<meta property="og:title" content="Runtime：方法调用与对象本质">
<meta property="og:url" content="https://bqlin.github.io/posts/runtime_method_call_and_object_essence/index.html">
<meta property="og:site_name" content="權咚领域">
<meta property="og:description" content="方法调用的流程： objc_msgSend调用方法的本质是通过isa指针找到该类，然后寻找方法，找到后调用。如果没有找到则通过superClass找到父类，继续查找方法。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/bqlin/image-land/raw/master/image-20211111175507815.png">
<meta property="article:published_time" content="2021-11-11T09:43:11.000Z">
<meta property="article:modified_time" content="2021-11-11T09:43:11.000Z">
<meta property="article:author" content="權咚">
<meta property="article:tag" content="Apple">
<meta property="article:tag" content="Objective-C">
<meta property="article:tag" content="Runtime">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/bqlin/image-land/raw/master/image-20211111175507815.png">

<link rel="canonical" href="https://bqlin.github.io/posts/runtime_method_call_and_object_essence/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Runtime：方法调用与对象本质 | 權咚领域</title>
  
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-105338942-1"></script>
    <script>
      if (CONFIG.hostname === location.hostname) {
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'UA-105338942-1');
      }
    </script>


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?98fcf61fd269408d07dcbc1e49311f9a";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="權咚领域" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">權咚领域</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Making app a work of art.</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://bqlin.github.io/posts/runtime_method_call_and_object_essence/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/icon.png">
      <meta itemprop="name" content="權咚">
      <meta itemprop="description" content="🤘🤯👾">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="權咚领域">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Runtime：方法调用与对象本质
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-11-11 17:43:11" itemprop="dateCreated datePublished" datetime="2021-11-11T17:43:11+08:00">2021-11-11</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span><br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>6.8k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>6 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>方法调用的流程：</p>
<p><code>objc_msgSend</code>调用方法的本质是通过isa指针找到该类，然后寻找方法，找到后调用。如果没有找到则通过<code>superClass</code>找到父类，继续查找方法。</p>
<p>对象结构体中的isa指向类对象。类对象的isa指向元类。元类的isa指向NSObject的元类。</p>
<p>对象方法是保存在类对象的结构体中，所以调用实例方法时，要去类对象中查找。以此类推，类方法也是如此。</p>
<p>实例对象存放isa指针以及示例变量，通过isa指针可以找到实例对象所属的类对象。类中存放着方法列表。方法列表中SEL作为key，IMP作为value。在编译期间，根据方法名字会生成唯一的标识SEL。IMP是指向最终函数实现的函数指针。整个Runtime的核心是<code>objc_msgSend</code>函数，通过给类发送SEL传递消息，找到匹配的IMP再获得最终的实现，并执行方法。</p>
<p><strong>消息发送阶段</strong>：</p>
<ol type="1">
<li>判断receiver是否为空，是则直接返回，否则继续。</li>
<li>从receiverClass的缓存中，查找方法找到则调用方法，否则继续。</li>
<li>从receiverClass的<code>class_rw_t</code>中查找方法，如果找到了则缓存下来，调用方法，否则继续。</li>
<li>去父类的缓存和<code>class_rw_t</code>中查找，步骤同上，找到了则缓存下来，没有则继续往上找父类，都没有则消息发送阶段结束，进入第二阶段：动态方法解析。</li>
</ol>
<p><strong>动态方法解析阶段</strong>：</p>
<p>调用<code>-/+resolveClassMethod:</code>，在方法中调用<code>class_addMethod</code>函数添加SEL对应的方法实现IMP。以上方法中没有处理，则进入第三阶段：消息转发。</p>
<p><strong>消息转发阶段</strong>：</p>
<ol type="1">
<li>判断<code>-/+forwardingTargetForSelector:</code>的返回值，非空则调用<code>objc_msgSend(返回值, SEL)</code>，向返回值发送消息。返回空则继续。</li>
<li>调用<code>-/+methodSignatureForSelector:</code>方法，如果返回不为空，则调用<code>-/+forwardInvocation:</code>方法中处理。若本类无法处理则继续往父类查询。如果返回空，则继续。</li>
<li>调用<code>-doesNotRecognizeSelector:</code>方法。</li>
</ol>
<p>注意：只能对运行时动态创建的类添加成员变量（ivars），不能向已存在的类添加成员变量。因为在编译时只读的class_ro_t结构体就被确定下来，其包含了分配对象的空间大小，在运行时不可改变。</p>
<h3 id="nsproxy">NSProxy</h3>
<p>NSProxy和NSObject是同一层级的，可以理解为NSProxy是一个基类，都遵循了NSObject协议。NSProxy就是专门用来解决重点对象转发的问题。</p>
<p>与NSObject接收消息流程不一样，NSProxy简化了其中的流程：</p>
<ol type="1">
<li><code>[proxyObj message]</code></li>
<li>到proxyObj类对象寻找对应的方法，找到调用。否则继续。</li>
<li>尝试调用<code>resolveClassMethod</code>进行动态方法解析</li>
<li><del>尝试进入父类对象递归查找方法，找到调用。否则继续。</del></li>
<li><del>尝试调用<code>forwardingTargetForSelector</code>进行消息转发。返回空则继续。</del></li>
<li>尝试调用<code>methodSignatureForSelector</code>+<code>forwardInvocation</code>进行消息转发。</li>
</ol>
<p>所以对于处理消息转发，它比NSObject更高效。也阐明了该类的使用方式就是实现消息转发的两个方法即可。</p>
<p>注意，无需调用init方法。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">#import &quot;CLProxy2.h&quot;</span><br><span class="line"></span><br><span class="line">@implementation CLProxy2</span><br><span class="line"></span><br><span class="line">+(instancetype)proxyWithTarget: (id)target &#123;</span><br><span class="line">	// NSProxy对象不需要调用init，因为它本来就没有init方法，直接alloc之后就可以使用</span><br><span class="line">    CLProxy2 *proxy = [CLProxy2 alloc];</span><br><span class="line">    proxy.target = target;</span><br><span class="line">    return proxy;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">-(NSMethodSignature *)methodSignatureForSelector:(SEL)sel &#123;</span><br><span class="line">    return [self.target methodSignatureForSelector:sel];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">-(void)forwardInvocation:(NSInvocation *)invocation &#123;</span><br><span class="line">    invocation.target = self.target;</span><br><span class="line">    [invocation invoke];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">@end</span><br></pre></td></tr></table></figure>
<h2 id="isa">isa</h2>
<p>从arm64架构开始，isa变成了一个共用体（union）结果，使用位域来存储更多信息。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">union</span> <span class="title">isa_t</span> &#123;</span></span><br><span class="line">    <span class="type">isa_t</span>() &#123; &#125;</span><br><span class="line">    <span class="type">isa_t</span>(<span class="type">uintptr_t</span> value) : bits(value) &#123; &#125;</span><br><span class="line"></span><br><span class="line">    Class cls;</span><br><span class="line">    <span class="type">uintptr_t</span> bits;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> &#123;</span></span><br><span class="line">        ISA_BITFIELD;  <span class="comment">// defined in isa.h</span></span><br><span class="line">    &#125;;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">define ISA_BITFIELD                                                      \</span><br><span class="line">      <span class="type">uintptr_t</span> nonpointer        : <span class="number">1</span>;   <span class="comment">//指针是否优化过                                   \</span></span><br><span class="line"><span class="comment">      uintptr_t has_assoc         : 1;   //是否有设置过关联对象，如果没有，释放时会更快                                   \</span></span><br><span class="line"><span class="comment">      uintptr_t has_cxx_dtor      : 1; 	 //是否有C++的析构函数（.cxx_destruct），如果没有，释放时会更快                                     \</span></span><br><span class="line"><span class="comment">      uintptr_t shiftcls          : 33; //存储着Class、Meta-Class对象的内存地址信息 \</span></span><br><span class="line"><span class="comment">      uintptr_t magic             : 6;  //用于在调试时分辨对象是否未完成初始化                                     \</span></span><br><span class="line"><span class="comment">      uintptr_t weakly_referenced : 1;  //是否有被弱引用指向过，如果没有，释放时会更快                                     \</span></span><br><span class="line"><span class="comment">      uintptr_t deallocating      : 1;  //对象是否正在释放                                     \</span></span><br><span class="line"><span class="comment">      uintptr_t has_sidetable_rc  : 1;  //引用计数器是否过大无法存储在isa中                                     \</span></span><br><span class="line"><span class="comment">      uintptr_t extra_rc          : 19 //里面存储的值是引用计数器减1</span></span><br><span class="line"><span class="meta">#   	<span class="keyword">define</span> RC_ONE   (1ULL&lt;&lt;45)</span></span><br><span class="line"><span class="meta">#   	<span class="keyword">define</span> RC_HALF  (1ULL&lt;&lt;18)</span></span><br></pre></td></tr></table></figure>
<ul>
<li><code>nonpointer</code>：0：普通指针，存储着Class、Meta-Class对象的内存地址；1：优化过，使用位域存储更多的信息。</li>
<li><code>has_assoc</code>：是否有关联过对象。否：释放更快。</li>
<li><code>has_cxx_dtor</code>：是否有C++析构函数（.cxx_destruct）。否：释放更快。</li>
<li><code>shiftcls</code>：存储着Class、Meta-Class对象的内存地址信息。</li>
<li><code>magic</code>：调试时分辨是否完成初始化。</li>
<li><code>weakly_referenced</code>：是否被弱引用指向过。否：释放更快。</li>
<li><code>deallocating</code>：对象是否正在释放。</li>
<li><code>extra_rc</code>：引用计数器-1。</li>
<li><code>has_sidetable_rc</code>：引用计数器是否过大无法存储在isa中。1：引用计数器会存储在SideTable类的属性中。</li>
</ul>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> *<span class="title function_">objc_destructInstance</span><span class="params">(id obj)</span> </span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">if</span> (obj) &#123;</span><br><span class="line">        <span class="comment">//是否有C++的析构函数</span></span><br><span class="line">        <span class="type">bool</span> cxx = obj-&gt;hasCxxDtor();</span><br><span class="line">        <span class="comment">//是否有设置过关联对象</span></span><br><span class="line">        <span class="type">bool</span> assoc = obj-&gt;hasAssociatedObjects();</span><br><span class="line">        <span class="comment">//有C++的析构函数，就去销毁</span></span><br><span class="line">        <span class="keyword">if</span> (cxx) object_cxxDestruct(obj);</span><br><span class="line">         <span class="comment">//有设置过关联对象，就去移除管理对象</span></span><br><span class="line">        <span class="keyword">if</span> (assoc) _object_remove_assocations(obj);</span><br><span class="line">        </span><br><span class="line">        obj-&gt;clearDeallocating();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> obj;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="class">class</h2>
<figure>
<img src="https://gitee.com/bqlin/image-land/raw/master/image-20211111175507815.png" alt="image-20211111175507815" /><figcaption aria-hidden="true">image-20211111175507815</figcaption>
</figure>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">objc_object</span> &#123;</span></span><br><span class="line">    Class _Nonnull isa  OBJC_ISA_AVAILABILITY;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">objc_class</span> :</span> objc_object &#123;</span><br><span class="line">    <span class="comment">// Class ISA;</span></span><br><span class="line">    Class superclass;</span><br><span class="line">    <span class="type">cache_t</span> cache;    <span class="comment">//方法缓存</span></span><br><span class="line">    <span class="type">class_data_bits_t</span> bits;    <span class="comment">// 用于获取具体的类的信息</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>method_array_t、property_array_t、protocol_array_t是可读写的二维数组，包含了类的初始内容、分类内容。</p>
<p>如：method_array_t包含多个一位数组method_list_t，method_list_t里面存放多个method_t，method_t存放在方法imp指针、名称、类型等信息。</p>
<h3 id="method_t">method_t</h3>
<p>方法、函数的封装。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">method_t</span> &#123;</span></span><br><span class="line">    SEL name; <span class="comment">// 函数名</span></span><br><span class="line">    <span class="type">const</span> <span class="type">char</span> *types; <span class="comment">// Type Encoding 编码(返回值类型，参数类型)</span></span><br><span class="line">    MethodListIMP imp; <span class="comment">// 指向函数的指针(函数地址)</span></span><br><span class="line"></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">SortBySELAddress</span> :</span></span><br><span class="line">        public <span class="built_in">std</span>::binary_function&lt;<span class="type">const</span> <span class="type">method_t</span>&amp;,</span><br><span class="line">                                    <span class="type">const</span> <span class="type">method_t</span>&amp;, <span class="type">bool</span>&gt;</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="type">bool</span> <span class="title function_">operator</span><span class="params">()</span> <span class="params">(<span class="type">const</span> <span class="type">method_t</span>&amp; lhs,</span></span><br><span class="line"><span class="params">                         <span class="type">const</span> <span class="type">method_t</span>&amp; rhs)</span></span><br><span class="line">        &#123; <span class="keyword">return</span> lhs.name &lt; rhs.name; &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>IMP：函数的具体实现。</p>
<p>SEL：方法、函数名，底层结构与<code>char *</code>类似。可以通过<code>@selector()</code>和<code>sel_registerName()</code>获得。可以通过<code>sel_getName()</code>和<code>NSStringFromSelector()</code>转成字符串。名字相同的方法，SEL也是相同的。</p>
<h3 id="class_ro_t">class_ro_t</h3>
<p>描述的是类的初始内容，其中的<code>baseMethodList</code>、<code>baseProtocols</code>、<code>ivars</code>、<code>baseProperties</code>是只读的一维数组。</p>
<h3 id="cache_t">cache_t</h3>
<p>方法缓存。用哈希表缓存调用过的方法，可以提高方法查找速度。</p>
<p>当方法缓存太多的时候，超过了表容量的3/4的时候，就要扩容为原来的2倍。</p>
<h2 id="类的本质">类的本质</h2>
<p>一个NSObject的本质是包含一个isa指针的结构体：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">struct NSObject_IMPL &#123;</span><br><span class="line">	Class isa;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>而其子类是在isa指针的基础上再加上自身的成员变量：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">struct Student_IMPL &#123;</span><br><span class="line">    struct NSObject_IMPL NSObject_IVARS;</span><br><span class="line">    int _age;</span><br><span class="line">    int _no;  </span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>所以一个子类的底层结构体是其父类结构体里的所有成员变量 + 子类自身定义的成员变量所组成的结构体。</p>
<p><code>class_getInstanceSize</code>：获取OC类实例对象的实际大小。这个大小可以理解为该实例对象至少需要的空间大小，实际分配大小需要使用<code>malloc_size</code>。</p>
<p><code>malloc_size</code>：得到一个指针指向的内存空间大小，这是系统为这个对象最终分配的内存大小。</p>
<p>所以回到问题：一个NSObject对象占用多少内存？</p>
<ul>
<li>系统分配了16字节（通过<code>malloc_size</code>获取）；</li>
<li>NSObject内部只使用了8个字节来存放isa指针变量。</li>
</ul>
<h2 id="对象的种类">对象的种类</h2>
<p>OC对象主要分为3类：</p>
<ul>
<li>实例对象（instance）</li>
<li>类对象（class）</li>
<li>元类对象（meta-class）</li>
</ul>
<p>实例对象通过类<code>alloc</code>方法创建出来。存放的信息：</p>
<ul>
<li><code>isa</code>指针（指向类）。</li>
<li>成员变量。</li>
</ul>
<p>类对象在内存中是唯一。的类对象用来描述一个实例对象，存放信息：</p>
<ul>
<li><code>isa</code>指针（指向元类）和<code>superclass</code>指针</li>
<li>属性</li>
<li>对象方法</li>
<li>协议</li>
<li>成员变量</li>
</ul>
<p>元类对象在内存中也是唯一的。元类对象用来描述一个类对象，存放信息：</p>
<ul>
<li><code>isa</code>指针和<code>superclass</code>指针（指向该类父类的元类）</li>
<li>类方法</li>
</ul>
<p>类和元类都是objc_class（继承自objc_object），也有isa指针，也是对象。</p>
<p>元类的<code>superclass</code>指向基类的类对象，者决定了：</p>
<p>当我们调用一个类方法时，会通过类的isa指针找到元类，在元类中查找有无该类方法，如果没有则通过<code>superclass</code>逐级查询父元类，一直找到基类的元类，如果还没有，则去找基类中的同名的实例方法实现。</p>
<h2 id="super">super</h2>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Person</span>: <span class="title class_">NSObject</span> &#123;&#125;</span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Student</span>: <span class="title class_">Person</span> &#123;</span><br><span class="line">    <span class="keyword">override</span> <span class="keyword">init</span>() &#123;</span><br><span class="line">        <span class="keyword">super</span>.<span class="keyword">init</span>()</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;className: <span class="subst">\(<span class="keyword">self</span>.className)</span>, super.className: <span class="subst">\(<span class="keyword">super</span>.className)</span>&quot;</span>)</span><br><span class="line">        <span class="comment">// FoundationSwift.Student, FoundationSwift.Student</span></span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;superclass: <span class="subst">\(<span class="keyword">self</span>.super<span class="keyword">class</span><span class="operator">!</span>)</span>, super.superclass: <span class="subst">\(<span class="keyword">super</span>.super<span class="keyword">class</span><span class="operator">!</span>)</span>&quot;</span>)</span><br><span class="line">        <span class="comment">// superclass: Person, super.superclass: Person</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>从上面发现， super和self调用的结构都是相同的。</p>
<p>super调用方法实际上是调用了<code>objc_msgSendSuper(arg, SEL)</code>函数。重点是第一个参数，其类型是<code>__rw_objc_super</code>：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">//♥️♥️♥️C++中间代码里的定义</span><br><span class="line">struct __rw_objc_super &#123; </span><br><span class="line">	struct objc_object *object; </span><br><span class="line">	struct objc_object *superClass; </span><br><span class="line">	__rw_objc_super(struct objc_object *o, struct objc_object *s) : object(o), superClass(s) &#123;&#125; </span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">//⚠️⚠️⚠️objc源码中的定义</span><br><span class="line">/// Specifies the superclass of an instance. </span><br><span class="line">struct objc_super &#123;</span><br><span class="line">    /// Specifies an instance of a class.</span><br><span class="line">    __unsafe_unretained _Nonnull id receiver;</span><br><span class="line"></span><br><span class="line">    /// Specifies the particular superclass of the instance to message. </span><br><span class="line">#if !defined(__cplusplus)  &amp;&amp;  !__OBJC2__</span><br><span class="line">    /* For compatibility with old objc-runtime.h header */</span><br><span class="line">    __unsafe_unretained _Nonnull Class class;</span><br><span class="line">#else</span><br><span class="line">    __unsafe_unretained _Nonnull Class super_class;</span><br><span class="line">#endif</span><br><span class="line">    /* super_class is the first class to search */</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>objc_super结构体成员：</p>
<ul>
<li><code>id receiver</code>：消息接收者，实参传递的就是self，即Student对象。</li>
<li><code>Class super_class</code>：父类。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">id objc_msgSendSuper(struct objc_super *super, SEL op, ...)</span><br></pre></td></tr></table></figure>
<ul>
<li><code>struct objc_super *super</code>：结构体指针，内容是<code>&#123;消息接收者（recv）， 消息接收者的父类类对象（[[recv superclass] class]）&#125;</code>。<code>objc_msgSendSuper</code>会将消息接收者的父类对象作为消息查找的起点。</li>
<li><code>SEL op</code>：要查找的方法。</li>
</ul>
<p>所以说，调用super与调用self的不同只是super把查找方法的起点改为从父类开始而已，所以像一些父类没有实现，而NSObject基类实现的方法，两者调用结果无异，因为最终的消息接收者还是self，即当前对象。</p>
<p>若要想super和self调用方法结果不一致，必须是当前类和父类都实现了相同的方法，若只有父类实现了，就都是父类的结果。这与一般方法查找父类实现的逻辑一致。</p>
<h2 id="参考">参考</h2>
<ul>
<li><a target="_blank" rel="noopener" href="https://juejin.cn/post/6844903793138597896">OC对象的本质（上）：OC对象的底层实现原理 - 掘金</a></li>
<li><a target="_blank" rel="noopener" href="https://juejin.cn/post/6963522983105134629">OC对象的本质（中）：OC对象的种类 - 掘金</a></li>
<li><a target="_blank" rel="noopener" href="https://juejin.cn/post/6963524896672464903">OC对象的本质（下）—— 详解isa&amp;superclass指针 - 掘金</a></li>
<li><a target="_blank" rel="noopener" href="https://juejin.cn/post/6844903474908364808">深入理解 Objective-C Runtime 机制 - 掘金</a></li>
</ul>

    </div>

    
    
    
        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Apple/" rel="tag"># Apple</a>
              <a href="/tags/Objective-C/" rel="tag"># Objective-C</a>
              <a href="/tags/Runtime/" rel="tag"># Runtime</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/posts/runtime_interview_question/" rel="prev" title="Runtime：综合面试题">
      <i class="fa fa-chevron-left"></i> Runtime：综合面试题
    </a></div>
      <div class="post-nav-item">
    <a href="/posts/lock/" rel="next" title="锁">
      锁 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="gitalk-container"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#nsproxy"><span class="nav-text">NSProxy</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#isa"><span class="nav-text">isa</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#class"><span class="nav-text">class</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#method_t"><span class="nav-text">method_t</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#class_ro_t"><span class="nav-text">class_ro_t</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#cache_t"><span class="nav-text">cache_t</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%B1%BB%E7%9A%84%E6%9C%AC%E8%B4%A8"><span class="nav-text">类的本质</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AF%B9%E8%B1%A1%E7%9A%84%E7%A7%8D%E7%B1%BB"><span class="nav-text">对象的种类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#super"><span class="nav-text">super</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%82%E8%80%83"><span class="nav-text">参考</span></a></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="權咚"
      src="/images/icon.png">
  <p class="site-author-name" itemprop="name">權咚</p>
  <div class="site-description" itemprop="description">🤘🤯👾</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">84</span>
          <span class="site-state-item-name">文章</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">10</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/bqlin" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;bqlin" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://weibo.com/hearingdog" title="Weibo → https:&#x2F;&#x2F;weibo.com&#x2F;hearingdog" rel="noopener" target="_blank"><i class="fab fa-weibo fa-fw"></i>Weibo</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://xiaozhuanlan.com/metal-reference-translation" title="https:&#x2F;&#x2F;xiaozhuanlan.com&#x2F;metal-reference-translation" rel="noopener" target="_blank">Metal内参</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://xiaozhuanlan.com/wwdc21" title="https:&#x2F;&#x2F;xiaozhuanlan.com&#x2F;wwdc21" rel="noopener" target="_blank">WWDC21 内参</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2016 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">權咚</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="站点总字数">279k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">4:14</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/pangu@4/dist/browser/pangu.min.js"></script>

<script src="/js/utils.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/js/local-search.js"></script>











<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme    : 'default',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>


  

  

  

<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.css">

<script>
NexT.utils.loadComments(document.querySelector('#gitalk-container'), () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js', () => {
    var gitalk = new Gitalk({
      clientID    : '7ed324dbfd2741c35c0e',
      clientSecret: '75a59e1f6a55202c4a1b0ec3570ad5b5dccbc390',
      repo        : 'bqlin.github.io',
      owner       : 'bqlin',
      admin       : ['bqlin'],
      id          : '7671ccc2c6c538168cddd5008f9f09b5',
        language: 'zh-CN',
      distractionFreeMode: true
    });
    gitalk.render('gitalk-container');
  }, window.Gitalk);
});
</script>

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"scale":1,"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","vOffset":-100},"mobile":{"show":false,"scale":0.5},"log":false});</script></body>
</html>
